package com.qianfeng.zhangwei.day46.utils;

import android.text.TextUtils;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.zhangwei.day46.bean.App;
import com.qianfeng.zhangwei.day46.bean.NearPoi;

import java.util.Collection;
import java.util.List;

/**
 * @说 明：
 * @项目名称：1506adc
 * @包 名： com.qianfeng.zhangwei.day39
 * @类 名：XUtilsHelper
 * @创 建人：zhangwei
 * @创建时间：2015-07-03 10 : 02
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class XUtilsTools {
    private static XUtilsTools tools;
    private HttpUtils httpUtils;
    private HttpHandler httpHandler;

    private XUtilsTools() {
        httpUtils = new HttpUtils();
    }

    public static XUtilsTools getInstance() {
        if (tools == null) {
            tools = new XUtilsTools();
        }
        return tools;
    }


    public <T> void get(String url, final BaseExpandableListAdapter adapter, final ExpandableListView expandableListView, final List<T> list, final TypeReference<App<T>> type) {
        httpHandler = httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                App app = JSONObject.parseObject(responseInfo.result, type);
                if (app != null && !TextUtils.isEmpty(app.getErrmsg()) && "success".equals(app.getErrmsg())) {
                    if (app.getData().getPoi_list() != null && !app.getData().getPoi_list().isEmpty()) {
                        List<NearPoi> nearPois = app.getData().getPoi_list();
                        list.addAll((Collection<? extends T>) nearPois);
                        adapter.notifyDataSetChanged();
                        for (int i = 0; i < adapter.getGroupCount(); i++) {
                            expandableListView.expandGroup(i);
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }
}
